package cn.unknowpupil.init.utils;

import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created at 2020/10/29 by w10g <br>
 * Initialize FileUtil ... <br>
 *
 * @author unknowpupil
 * @since 0.0.1
 */
public class FileUtil {

    /**
     * 获取文件路径
     * @param filename 文件名
     * @param pathName 文件夹名
     * @return
     */
    public static String getPath(String  filename,String pathName) {
        File file = new File(filename);
        if(!file .exists()){
            File b = new File(pathName);
            b.mkdir();
        }
        ClassPathResource classPathResource = new ClassPathResource(filename);
        try {
            InputStream inputStream =classPathResource.getInputStream();
            writeToLocal(filename,inputStream);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return   file.getAbsolutePath();


    }
    private static void writeToLocal(String destination, InputStream input)
            throws IOException {
        int index;
        byte[] bytes = new byte[1024];
        FileOutputStream downloadFile = new FileOutputStream(destination);
        while ((index = input.read(bytes)) != -1) {
            downloadFile.write(bytes, 0, index);
            downloadFile.flush();
        }
        downloadFile.close();
        input.close();
    }
}
